package com.artisan.springuitls.demos;

import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * StreamUtils 工具类演示
 * 功能：流操作轻量级专家
 * 优势：比 FileCopyUtils 更专注流处理，不依赖 IOUtils
 */
@Component
public class StreamUtilsDemo {

    /**
     * 场景：读取配置文件流，转为字符串
     */
    public String loadConfig(String resourcePath) throws Exception {
        System.out.println("\n========== StreamUtils Demo ==========");
        
        InputStream inputStream = getClass().getResourceAsStream(resourcePath);
        if (inputStream == null) {
            throw new FileNotFoundException("资源未找到: " + resourcePath);
        }
        
        // ✅ 一行转字符串：指定编码
        String config = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        System.out.println("配置内容长度: " + config.length() + " 字符");
        return config;
    }

    /**
     * 演示更多流操作方法
     */
    public void demonstrateMoreMethods() throws IOException {
        System.out.println("\n--- 各种流操作 ---");
        
        // 1. InputStream 转 String
        String text = "Spring Boot 工具类演示";
        ByteArrayInputStream inputStream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
        String result = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        System.out.println("✓ InputStream 转 String: " + result);
        
        // 2. String 转 OutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        StreamUtils.copy(text, StandardCharsets.UTF_8, outputStream);
        System.out.println("✓ String 转 OutputStream: " + outputStream.toString(StandardCharsets.UTF_8));
        
        // 3. InputStream 转 byte[]
        ByteArrayInputStream bais = new ByteArrayInputStream("测试数据".getBytes(StandardCharsets.UTF_8));
        byte[] bytes = StreamUtils.copyToByteArray(bais);
        System.out.println("✓ InputStream 转 byte[]: " + new String(bytes, StandardCharsets.UTF_8));
        
        // 4. 流拷贝（手动控制）
        ByteArrayInputStream source = new ByteArrayInputStream("源数据".getBytes(StandardCharsets.UTF_8));
        ByteArrayOutputStream target = new ByteArrayOutputStream();
        StreamUtils.copy(source, target);
        System.out.println("✓ 流拷贝结果: " + target.toString(StandardCharsets.UTF_8));
        
        // 5. 流排空（消费所有数据）
        ByteArrayInputStream drainStream = new ByteArrayInputStream("待排空数据".getBytes(StandardCharsets.UTF_8));
        int drainedBytes = StreamUtils.drain(drainStream);
        System.out.println("✓ 流排空字节数: " + drainedBytes);
        
        // 6. 获取非关闭的输入流包装器
        ByteArrayInputStream original = new ByteArrayInputStream("原始数据".getBytes(StandardCharsets.UTF_8));
        InputStream nonClosing = StreamUtils.nonClosing(original);
        nonClosing.close(); // 关闭包装器不会关闭原始流
        try {
            System.out.println("✓ 非关闭流可用字节: " + original.available());
        } catch (Exception e) {
            System.out.println("✗ 获取可用字节失败");
        }
        
        System.out.println("==========================================\n");
    }

    /**
     * 演示实际应用场景：HTTP 响应流处理
     */
    public void demonstrateHttpResponse() throws IOException {
        System.out.println("\n--- 模拟 HTTP 响应处理 ---");
        
        // 模拟 HTTP 响应体
        String httpResponse = "{\"status\":\"success\",\"data\":{\"id\":1001,\"name\":\"张三\"}}";
        ByteArrayInputStream responseStream = new ByteArrayInputStream(
            httpResponse.getBytes(StandardCharsets.UTF_8));
        
        // 读取响应
        String responseBody = StreamUtils.copyToString(responseStream, StandardCharsets.UTF_8);
        System.out.println("✓ HTTP 响应体: " + responseBody);
        
        System.out.println("==========================================\n");
    }
}

